package com.cowcowit.springcloud.controller;

import com.cowcowit.springcloud.entity.PayDTO;
import com.cowcowit.springcloud.result.ResultData;
import jakarta.annotation.Resource;
import org.springframework.http.*;
import org.springframework.web.bind.annotation.*;
import org.springframework.web.client.RestTemplate;


@RestController
public class OrderController {

    //服务注册中心上的微服务名称
    public static final String PaymentSrv_URL = "http://cloud-provider-payment8001";

    @Resource
    private RestTemplate restTemplate;

    // 测试通过POST方法
    @PostMapping(value = "/consumer/pay/add")
    public ResultData addOrder(PayDTO payDTO) {
        return restTemplate.postForObject(PaymentSrv_URL + "/pay/add", payDTO, ResultData.class);
    }

    // 根据ID删除order
    @DeleteMapping(value = "/consumer/pay/del/{id}")
    public ResultData deletePay(@PathVariable("id") Integer id) {
        // 假设远程服务支持DELETE请求
        ResponseEntity<ResultData> response = restTemplate.exchange(
                PaymentSrv_URL + "/pay/del/{id}",
                HttpMethod.DELETE,
                null,
                ResultData.class,
                id
        );
        return response.getBody();
    }

    // 修改 order
    @PutMapping(value = "/consumer/pay/update")
    public ResultData updatePay(@RequestBody PayDTO payDTO) {
        // 假设远程服务支持PUT请求
        HttpHeaders headers = new HttpHeaders();
        headers.setContentType(MediaType.APPLICATION_JSON);
        HttpEntity<PayDTO> request = new HttpEntity<>(payDTO, headers);

        // 使用exchange方法发送PUT请求并处理响应
        ResponseEntity<ResultData> response = restTemplate.exchange(
                PaymentSrv_URL + "/pay/update",
                HttpMethod.PUT,
                request,
                ResultData.class
        );
        return response.getBody();
    }

    // GET http://localhost:80/consumer/pay/get/1
    @GetMapping(value = "/consumer/pay/get/{id}")
    public ResultData getPayInfo(@PathVariable("id") Integer id) {
        return restTemplate.getForObject(PaymentSrv_URL + "/pay/get/" + id, ResultData.class, id);
    }

}